# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Block some property modifications:

- gvn:superusers on repository root
"""


import svn.fs


def DebugLog(hi, author, logger):
  props = svn.fs.node_proplist(hi.txn_root, "/", hi.pool)
  for property in props:
    logger.debug("Found property %s on repository root" % (property,))

def RunHook(hi, logger):
  """Implements gvn.hooks.runner's RunHook interface

  Returns:
    -1: pass and bypass other hooks
    0: pass
    1: fail
    "string": fail and print string to the user
  """

  # We only care about changes to the root of the repository
  if "/" not in hi.paths_changed:
    logger.debug("No changes to /, therefore no node properties to check, pass")
    return 0

  author = svn.fs.txn_prop(hi.txn, "svn:author", hi.pool)
  DebugLog(hi, author, logger)

  # Get current gvn:superusers value from HEAD.
  old = svn.fs.node_prop(hi.head_root, "", "gvn:superusers", hi.pool)
  if old is None:
    # There are no superusers currently; this user is setting the
    # initial value.  Let it through.
    return 0

  # Get new gvn:superusers value from the txn.
  new = svn.fs.node_prop(hi.txn_root, "", "gvn:superusers", hi.pool)

  if old != new:
    retstr = ("user %s cannot modify %s property on repository root"
              % (author, "gvn:superusers"))
    logger.warn(retstr)
    return retstr

  logger.info("all root properties changes accepted, success!")
  return 0
